import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { appService } from '../../../../../my-service/app.service';
import { UtilService } from '../../../../../my-service/util.service'
import { DomSanitizer } from '@angular/platform-browser'
declare var $: any;
declare var io: any;
@Component({
  selector: 'questioncanvas-root',
  templateUrl: './questioncanvas.component.html',
  styleUrls: ['./questioncanvas.component.css']
})
export class questioncanvasComponent implements OnInit {
  QuestionData = [];//左边的锚点
  socket;
  updata = false;
  canopenadd = false;//控制详情弹出框的
  pointerArray = [];
  SelectData = [{
    FK_CanvasGuid: '',
    Color: '',
    AnchorName: '',
    Subtitle: '',
    PK_AnchorGuid: '',
    Type: '',
    NoteHeight: '',
    NoteWidth: '',
    InnerHtml: '',
    Coordinate: {
      x: '',
      y: ''
    },   //右边的选择了的数据
    PK_CanvasGroupGuid: '',
    QuestionList: [{
      PK_NoteGuid: '',
      name: '',
      FK_CanvasGroupGuid: '',
      Content: '点击输入问题',
      Color: '',
      PK_AnchorGuid: '',
      title: '',
      updata: false
    }],
    index: 0
  }];
  addwindow = false;
  config = {
    HaveTitle: 0,
    HaveAuthor: 0,
    PK_AnchorGuid: ''
  }
  NoteDataSuccess = false;
  QuestDataSuccess = false;
  index: number = 0;
  dropLine=0;
  LoadBoxData = false;
  private pointdata: any;//单个的锚点数据，准备传给详情弹出框
  private notedata: any;//标签数据，准备传给详情弹出框
  @Input() CanvasGroupGuid: any;
  @Input() mainH: any;
  @Input() mainW: any;
  @Output() deldata = new EventEmitter<Event>();
  constructor(
    private sanitizer: DomSanitizer,
    private appservice: appService,
    private UtilService: UtilService,
  ) { }
  ngOnInit() {
    this.getpoint();
    this.getquestion();
    //socket监听
    this.socket = io('ws://47.106.117.200:6101/');
    // this.socket = io('ws://localhost:6101/');
    // this.socket = io('ws://211.149.221.44:6101/');
    // this.socket = io('ws://132.232.143.47:6101/');

    this.socket.on('connect', () => {
      this.socket.emit('Host', { FK_CanvasGroupGuid: this.CanvasGroupGuid })
    })
    this.socket.on('disconnect', () => {
      this.dropLine++
      if(this.dropLine>1){
          this.UtilService.remind("error","网络动荡，已刷新！")
          location.reload();
      }
    })

    this.socket.on('re', (re) => {
      this.appservice.getonenote(re.PK_NoteGuid).then((re) => {
        for (let i = 0; i < this.SelectData.length; i++) {
          if (this.SelectData[i].PK_AnchorGuid == re.FK_AnchorGuid) {
            this.SelectData[i].QuestionList.push({
              PK_NoteGuid: re.PK_NoteGuid,
              name: re.Name,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Content: re.Content,
              Color: re.Color,
              PK_AnchorGuid: re.FK_AnchorGuid,
              title: re.Title,
              updata: true
            })
          }
        }
        this.pointerArray.forEach(element => {//遍历锚点
          if (element.PK_AnchorGuid == re.FK_AnchorGuid) {//如果锚点guid与note的guid相同
            element.note.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: re.PK_NoteGuid,
              Name: re.Name,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Content: re.Content,
              Color: re.Color,
              FK_AnchorGuid: re.FK_AnchorGuid,
              Title: re.Title
            })
            let min = element.Coordinate[0].note;//设置最小值数组用来存新添加的标签
            for (let i = 0; i < element.Coordinate.length; i++) {//遍历锚点中的坐标
              if (element.Coordinate[i].note.length < min.length) {//如果锚点中的坐标中的标签的数量小于最小值标签
                min = element.Coordinate[i].note;//则更新最小值标签
              }
            }
            min.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: re.PK_NoteGuid,
              Name: re.Name,
              Content: re.Content,
              Color: re.Color,
              FK_AnchorGuid: re.FK_AnchorGuid,
              Title: re.Title
            })
          }
        });
      })
    })
  }
  innerh5(h5) {
    return this.sanitizer.bypassSecurityTrustHtml(h5)
  }
  /*-----------------------------------------------------note初始化开始------------------------------------------------------------------------*/
  getpoint() {
    let notere = [];
    this.appservice.getPointer(this.CanvasGroupGuid).then(re => {
      for (let i = 0; i < re.length; i++) {
        if (re[i].Type == "note") {
          notere.push(re[i])
        }
      }
      notere.forEach(element => {
        element.Coordinate = JSON.parse(element.Coordinate)
        element.AddCoordinate = JSON.parse(element.AddCoordinate)
        element.note = [];
        for (let j = 0; j < element.Coordinate.length; j++) {//遍历坐标值数组
          element.Coordinate[j].note = []; //初始化坐标值数组
        }
      });
      this.appservice.getallnote(this.CanvasGroupGuid).then((res) => {
        for (let i = 0; i < res.length; i++) {
          notere.forEach(element => {
            if (element.PK_AnchorGuid == res[i].FK_AnchorGuid) {
              element.note.push(res[i])
              let min = element.Coordinate[0].note;
              for (let i = 0; i < element.Coordinate.length; i++) {
                if (element.Coordinate[i].note.length < min.length) {
                  min = element.Coordinate[i].note;
                }
              }
              min.push(res[i]);
            }
          });
        }
        this.pointerArray = notere
      })
    }).then(() => {
      this.canopenadd = false;
      this.updata = false;
    }).then(() => {
      this.LoadBoxData = true;
      this.NoteDataSuccess = true;
    })
  }
  /*-----------------------------------------------------note初始化结束------------------------------------------------------------------------*/
  /*-----------------------------------------------------question初始化开始------------------------------------------------------------------------*/
  //获取锚点以及其数据
  getquestion() {
    this.appservice.getPointer(this.CanvasGroupGuid).then(re => {
      let questionre = [];
      for (let i = 0; i < re.length; i++) {
        if (re[i].Type == "question") {
          questionre.push(re[i])
        }
      }
      questionre.forEach(element => {
        element.select = false;
        element.img = element.Style;
        element.Coordinate = JSON.parse(element.Coordinate)[0];
        element.AddCoordinate = JSON.parse(element.AddCoordinate)[0];
      });
      this.QuestionData = questionre;
      this.QuestionData[0].select = true;
      for (let m = 0; m < questionre.length; m++) {
        this.SelectData[m] = {
          FK_CanvasGuid: this.QuestionData[m].FK_CanvasGuid,
          Color: this.QuestionData[m].Color,
          AnchorName: this.QuestionData[m].AnchorName,
          Subtitle: this.QuestionData[m].Subtitle,
          PK_AnchorGuid: this.QuestionData[m].PK_AnchorGuid,
          PK_CanvasGroupGuid: this.QuestionData[m].PK_CanvasGroupGuid,
          QuestionList: [],
          InnerHtml: this.QuestionData[m].InnerHtml,
          NoteHeight: this.QuestionData[m].NoteHeight,
          NoteWidth: this.QuestionData[m].NoteWidth,
          Coordinate: {
            x: this.QuestionData[m].Coordinate.x,
            y: this.QuestionData[m].Coordinate.y
          },
          Type: this.QuestionData[m].Type,
          index: m
        };
      }
      this.appservice.getallnote(this.CanvasGroupGuid).then((re) => {
        for (let i = 0; i < this.SelectData.length; i++) {
          for (let k = 0; k < re.length; k++) {
            if (this.SelectData[i].PK_AnchorGuid == re[k].FK_AnchorGuid) {
              this.SelectData[i].QuestionList.push({
                PK_NoteGuid: re[k].PK_NoteGuid,
                name: re[k].Name,
                FK_CanvasGroupGuid: re[k].FK_CanvasGroupGuid,
                Content: re[k].Content,
                Color: this.SelectData[i].Color,
                PK_AnchorGuid: re[k].FK_AnchorGuid,
                title: re[k].Title,
                updata: true
              })
            }
          }
        }
      })
    }).then(() => {
      this.QuestDataSuccess = true;
    })
  }
  /*--------------------------------------------------------question初始化结束---------------------------------------------------------------------*/
  /*-----------------------------------------------------note事件------------------------------------------------------------------------*/
  //删除
  del($event) {
    this.updata = true;
    this.appservice.delnote($event).then(re => {
      if (re.PK_NoteGuid) {
        for (let i = 0; i < this.pointerArray.length; i++) {
          for (let j = 0; j < this.pointerArray[i].Coordinate.length; j++) {
            for (let k = 0; k < this.pointerArray[i].Coordinate[j].note.length; k++) {
              if (re.PK_NoteGuid == this.pointerArray[i].Coordinate[j].note[k].PK_NoteGuid) {
                this.pointerArray[i].Coordinate[j].note.splice(k, 1);
              }
            }
          }
        }
      }
      return re
    }).then((re) => {
      for (let i = 0; i < this.pointerArray.length; i++) {
        for (let m = 0; m < this.pointerArray[i].note.length; m++) {
          if (re.PK_NoteGuid == this.pointerArray[i].note[m].PK_NoteGuid) {
            this.pointerArray[i].note.splice(m, 1);
          }
        }
      }
      return re.PK_NoteGuid
    }).then((re2) => {
      this.deldata.emit(re2)
    })
  }
  hover(k, j, length, decide) {
    if (length > 1 && decide) {
      $(`#point${k}hover${j}`).show(50);
    }
  }
  //hover事件结束
  hoverend(k, j, length, decide) {

    if (length > 1 && decide) {
      $(`#point${k}hover${j}`).hide(50);
    }
  }
  //打开详情界面
  openadd(pointer, length) {
    if (length > 0) {
      this.pointdata = pointer;
      this.canopenadd = true;
    }
    else { return }
  }
  //添加
  add($event) {
    this.updata = true;
    this.addwindow = true;
    this.config = {
      HaveAuthor: $event.HaveAuthor,
      HaveTitle: $event.HaveTitle,
      PK_AnchorGuid: $event.PK_AnchorGuid
    }
    // this.addnote($event.PK_AnchorGuid, $event.color, $event.HaveTitle, $event.HaveAuthor)
  }
  //关闭详情界面
  closeAdd() {
    if (this.updata) {
      this.getpoint()
    }
    else {
      this.canopenadd = false
    }
  }
  //标签添加框的事件
  oncancel() {
    this.addwindow = false;
    this.config = {
      HaveTitle: 0,
      HaveAuthor: 0,
      PK_AnchorGuid: ''
    }
  }
  onok(data) {
    this.addwindow = false;
    this.config = {
      HaveTitle: 0,
      HaveAuthor: 0,
      PK_AnchorGuid: ''
    }
    data.PK_NoteGuid = this.appservice.GenGuid();//生成新标签的guid
    data.FK_CanvasGroupGuid = this.CanvasGroupGuid;
    this.appservice.postnote(data).then(re => {//向数据库中标签表post数据
      if (re.status == "success") {
        this.pointerArray.forEach(element => {//遍历锚点
          if (element.PK_AnchorGuid == data.PK_AnchorGuid) {//如果锚点guid与note的guid相同
            element.note.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: data.PK_NoteGuid,
              Name: data.name,
              FK_CanvasGroupGuid: data.FK_CanvasGroupGuid,
              Content: data.Content,
              Color: data.color,
              FK_AnchorGuid: data.PK_AnchorGuid,
              Title: data.Title
            })
            let min = element.Coordinate[0].note;//设置最小值数组用来存新添加的标签
            for (let i = 0; i < element.Coordinate.length; i++) {//遍历锚点中的坐标
              if (element.Coordinate[i].note.length < min.length) {//如果锚点中的坐标中的标签的数量小于最小值标签
                min = element.Coordinate[i].note;//则更新最小值标签
              }
            }
            min.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: data.PK_NoteGuid,
              Name: data.name,
              Content: data.Content,
              Color: data.color,
              FK_AnchorGuid: data.PK_AnchorGuid,
              Title: data.Title
            })
          }
        });
      }
    })
  }
  // //添加标签
  addnote(PK_AnchorGuid, color, HaveTitle, HaveAuthor) {
    this.addwindow = true;
    this.config = {
      HaveAuthor: HaveAuthor,
      HaveTitle: HaveTitle,
      PK_AnchorGuid: PK_AnchorGuid
    }
  }
  /*-----------------------------------------------------note事件结束------------------------------------------------------------------------*/
  /*--------------------------------------------------------question事件---------------------------------------------------------------------*/
  //提交问题focus事件
  questionfocus(item) {
    if (item.Content == '点击输入问题') {
      item.Content = '';
    }
  }
  //提交问题blur事件
  questionblur(item, i) {
    if (item.Content !== '') {
      if (item.updata) {
        this.appservice.putnote(this.SelectData[this.index].QuestionList[i])
      }
      else {
        item.updata = true;
        this.appservice.postnote(this.SelectData[this.index].QuestionList[i])
      }
    }
  }
  //删除问题
  questiondel(item, index) {
    this.appservice.delnote(item.PK_NoteGuid).then((re) => {
      if (re.PK_NoteGuid) {
        for (let i = 0; i < this.SelectData[index].QuestionList.length; i++) {
          if (this.SelectData[index].QuestionList[i].PK_NoteGuid == re.PK_NoteGuid) {
            this.SelectData[index].QuestionList.splice(i, 1)
            this.UtilService.remind('success', '删除成功')
          }
        }
        this.deldata.emit(re.PK_NoteGuid)
      }
    })
  }
  //选择锚点
  select(index, item) {
    this.index = index;
    if (!item.select) {
      this.QuestionData.forEach(element => {
        element.select = false;
      });
      item.select = true;
    }
  }
  //添加问题
  questionadd(index) {
    this.SelectData[index].QuestionList.push({
      PK_NoteGuid: this.appservice.GenGuid(),
      name: null,
      FK_CanvasGroupGuid: this.CanvasGroupGuid,
      Content: '点击输入问题',
      Color: this.SelectData[index].Color,
      PK_AnchorGuid: this.SelectData[index].PK_AnchorGuid,
      title: '',
      updata: false
    })
  }
  recovery(PK_NoteGuid) {
    this.appservice.getonenote(PK_NoteGuid).then((re) => {
      if (re.Type == 'question') {
        this.SelectData.forEach(element => {
          if (element.PK_AnchorGuid == re.FK_AnchorGuid) {
            element.QuestionList.push({
              PK_NoteGuid: re.PK_NoteGuid,
              name: re.Name,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Content: re.Content,
              Color: re.Color,
              PK_AnchorGuid: re.FK_AnchorGuid,
              title: re.Title,
              updata: true
            })
          }
        });
      }
      else if (re.Type == 'note') {
        this.pointerArray.forEach(element => {
          if (element.PK_AnchorGuid == re.FK_AnchorGuid) {
            element.note.push({
              Content: re.Content,
              FK_AnchorGuid: re.FK_AnchorGuid,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Name: re.Name,
              PK_NoteGuid: re.PK_NoteGuid,
              Title: re.Title
            })
            let min = element.Coordinate[0].note;
            for (let i = 0; i < element.Coordinate.length; i++) {
              if (element.Coordinate[i].note.length < min.length) {
                min = element.Coordinate[i].note;
              }
            }
            min.push({
              Content: re.Content,
              FK_AnchorGuid: re.FK_AnchorGuid,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Name: re.Name,
              PK_NoteGuid: re.PK_NoteGuid,
              Title: re.Title
            });
          }
        });
      }
    })
  }
  //13是极限
  charts(CanvasType, Name, chartsType) {
    let notelength = 5
    let chartsData = { "name": Name, "children": [] }
    let questionLength = this.SelectData.length;
    for (let i = 0; i < this.SelectData.length; i++) {
      chartsData.children.push({
        'name': this.SelectData[i].AnchorName,
        'children': []
      })
      if (this.SelectData[i].QuestionList.length < 5) notelength = this.SelectData[i].QuestionList.length
      for (let j = 0; j < this.SelectData[i].QuestionList.length; j++) {
        let _content = this.SelectData[i].QuestionList[j].Content;
        _content = _content.replace(/[\r\n]/g, " ")
        if (chartsType == 'charts' && _content.length > 46) {
          _content = _content.substring(0, 46) + '......'
        }
        chartsData.children[i].children.push({
          'name': _content
        })
      }
    }
    for (let m = 0; m < this.pointerArray.length; m++) {
      chartsData.children.push({
        'name': this.pointerArray[m].AnchorName,
        'children': []
      })
      if (this.pointerArray[m].note.length < 5) notelength = this.pointerArray[m].note.length
      for (let k = 0; k < this.pointerArray[m].note.length; k++) {
        let _content2 = this.pointerArray[m].note[k].Content
        _content2 = _content2.replace(/[\r\n]/g, " ")
        if (chartsType == 'charts' && _content2.length > 46) {
          _content2 = _content2.substring(0, 46) + '......'
        }
        chartsData.children[m + questionLength].children.push({
          'name': _content2
        })
      }
    }
    return chartsData
  }
  /*--------------------------------------------------------question事件结束---------------------------------------------------------------------*/
}
